//
//  HZSingleStockView.m
//  HZTC_Stock
//
//  Created by MayerF on 17/3/13.
//  Copyright © 2017年 MayerF. All rights reserved.
//

#import "HZSingleStockView.h"
#import "HZMinChartView.h"
#import "HZKLineChartView.h"
#import "HZDataTool.h"
#import "HZMarketBottomBarView.h"

#import "HZLandscapeChartView.h"
#import "HZStockInfoView.h"

@interface HZSingleStockView()<UIScrollViewDelegate>
@property (nonatomic, strong)UIScrollView *pScrollView;
@property (nonatomic, strong)UIView *pContentSizeView;
@property (nonatomic, strong)UIImageView *pLeftImageView;
@property (nonatomic, strong)UIImageView *pRightImageView;
@property (nonatomic, strong)UIPageControl *pPageControl;

@property (nonatomic, strong)NSMutableArray *pCacheArray;//缓存视图对象
@property (nonatomic, strong)NSArray *pLoopViewsArray;

@property (nonatomic, assign)NSInteger nLeftIndex;
@property (nonatomic, assign)NSInteger nRightIndex;

@property (nonatomic, strong)HZMarketBottomBarView *pMarketBottomBar;

@property (nonatomic, strong)HZLandscapeChartView *pLandscapeChartView;
@property (nonatomic, assign)CGFloat nOffsetMin; //横屏前的分时所在偏移量
@property (nonatomic, assign)CGFloat nOffsetKline; //横屏前的k所在偏移量
@property (nonatomic, assign)BOOL isLandscape;//进入横屏

@property (nonatomic, strong)HZMinPriceModel *pMinPriceModel;
@property (nonatomic, strong)HZMinPriceModel *pKPriceModel;
@property (nonatomic, strong)HZOwnedStockModel *pOwnModel;
@end

@implementation HZSingleStockView
- (UIView *)p_loadMarketBottomBarView
{
    if (!_pMarketBottomBar) {
        _pMarketBottomBar = [HZMarketBottomBarView new];
        _pMarketBottomBar.logicManager = self.logicManager;
        [self addSubview:_pMarketBottomBar];
        if (IPHONE_X) {
            [_pMarketBottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.mas_equalTo(self);
                make.bottom.mas_equalTo(self).offset(-34);
                make.height.mas_equalTo(45);
            }];
        }else {
            [_pMarketBottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.right.bottom.mas_equalTo(self);
                make.height.mas_equalTo(45);
            }];
        }
    }
    
    return _pMarketBottomBar;
}
- (void)p_loadLandscapeChartView
{
    if (!_pLandscapeChartView) {
        _pLandscapeChartView = [HZLandscapeChartView new];
        _pLandscapeChartView.parent = self;
        [self addSubview:_pLandscapeChartView];
        [_pLandscapeChartView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self);
        }];
        
    }
    [self bringSubviewToFront:_pLandscapeChartView];
}
#pragma mark -
#pragma mark lazy
- (UIPageControl *)pPageControl
{
    if (!_pPageControl) {
        _pPageControl = [UIPageControl new];
        _pPageControl.userInteractionEnabled = NO;
        [self setPageColor:kMYHexToRGB(0xffffff, 1) andCurrentPageColor:kMYHexToRGB(0x305895, 1)];
        [self addSubview:_pPageControl];
        [_pPageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self);
            make.bottom.mas_equalTo(self).offset(-3);
            make.width.mas_equalTo(50);
            make.height.mas_equalTo(10);
        }];
        _pPageControl.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.7, 0.7);
    }
    return _pPageControl;
}
// 设置pageControl的指示器图片
- (void)setPageImage:(UIImage *)image andCurrentPageImage:(UIImage *)currentImage {
    if (!image || !currentImage) return;
    //    self.pageImageSize = image.size;
    [self.pPageControl setValue:currentImage forKey:@"_currentPageImage"];
    [self.pPageControl setValue:image forKey:@"_pageImage"];
}
// 设置pageControl的指示器颜色
- (void)setPageColor:(UIColor *)color andCurrentPageColor:(UIColor *)currentColor {
    self.pPageControl.pageIndicatorTintColor = color;
    self.pPageControl.currentPageIndicatorTintColor = currentColor;
}
#pragma mark -
#pragma mark 生命周期
- (instancetype)init{
    self = [super init];
    if (self) {
        [self p_commonInit];
        self.backgroundColor = [HZCommonTool getThemeColor];
    }
    return self;
}
#pragma mark -
#pragma mark public
- (void)showLoopViews:(NSArray<Class> *)loopViews
{
    _pLoopViewsArray = loopViews;
    _pScrollView.scrollEnabled = YES;
    if (loopViews.count == 0) {return;}
    if (loopViews.count == 1) {
        _pScrollView.scrollEnabled = NO;
        [self bindBaseView:_pLeftImageView withLoopView:loopViews[0]];
    }else {
        _nLeftIndex = 0;
        _nRightIndex = 1;
        [self updateLoopView];
    }
    //pagecontrol
    self.pPageControl.numberOfPages = loopViews.count;
    self.pPageControl.currentPage = 0;
}
#pragma mark -
#pragma mark UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self p_scrollWithOffsetX:scrollView.contentOffset.x];
}
- (void)p_scrollWithOffsetX:(CGFloat)offsetX
{
    //调整图片切换逻辑
    if (offsetX < 0) {
        _pScrollView.contentOffset = CGPointMake(CGRectGetWidth(self.frame), 0);
        _nRightIndex = _nLeftIndex;
        _nLeftIndex = _nLeftIndex - 1 < 0 ? (_pLoopViewsArray.count - 1) : _nLeftIndex - 1;
        [self updateLoopView];
    }else if (offsetX > CGRectGetWidth(self.frame)) {
        _pScrollView.contentOffset = CGPointMake(0, 0);
        _nLeftIndex = _nRightIndex;
        _nRightIndex = _nRightIndex + 1 > (_pLoopViewsArray.count-1) ? (0) : _nRightIndex + 1;
        [self updateLoopView];
    }
    //调整PageControl切换逻辑
    if (offsetX > CGRectGetWidth(self.frame)/2 || offsetX > CGRectGetWidth(self.frame)*3/2) {
        self.pPageControl.currentPage = _nRightIndex;
    }else if (offsetX < CGRectGetWidth(self.frame)/2) {
        self.pPageControl.currentPage = _nLeftIndex;
    }
}
//更新视图
- (void)updateLoopView
{
    if (_nLeftIndex > _pLoopViewsArray.count || _nRightIndex > _pLoopViewsArray.count) {
        return;
    }
    [self bindBaseView:_pLeftImageView withLoopView:_pLoopViewsArray[_nLeftIndex]];
    [self bindBaseView:_pRightImageView withLoopView:_pLoopViewsArray[_nRightIndex]];
}
//绑定视图
- (void)bindBaseView:(UIView *)baseView withLoopView:(Class)loopViewClass
{
    for (UIView *subView in baseView.subviews) {
        [subView removeFromSuperview];
    }
    UIView *loopView = [self getLoopView:loopViewClass];
    [baseView addSubview:loopView];
    [loopView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(baseView);
    }];
}
//获取loopview
- (UIView *)getLoopView:(Class)loopViewClass
{
    UIView *resultView = nil;
    for (UIView *cacheView in _pCacheArray) {
        if ([cacheView isMemberOfClass:loopViewClass]) {
            resultView = cacheView;
            break;
        }
    }
    if (!resultView) {//如果没有缓存
        resultView = [loopViewClass new];
        if ([resultView isKindOfClass:[HZBaseMarketView class]]) {
            HZBaseMarketView *newView = (HZBaseMarketView *)resultView;
            newView.parent = self;
            if ([resultView isKindOfClass:[HZStockInfoView class]]) {
                HZStockInfoView *stockView = (HZStockInfoView *)resultView;
                [stockView loadStockInfoWithCode:_pOwnModel.model_Code];
            }
        }
        [_pCacheArray addObject:resultView];
    }
    return resultView;
}
#pragma mark -
#pragma mark private
- (void)p_commonInit
{
    _pScrollView = [UIScrollView new];
    _pContentSizeView = [UIView new];
    _pLeftImageView = [UIImageView new];
    _pRightImageView = [UIImageView new];
    _pLeftImageView.userInteractionEnabled = YES;
    _pRightImageView.userInteractionEnabled = YES;
    
    _pScrollView.delegate = self;
    _pScrollView.pagingEnabled = YES;
    _pScrollView.showsHorizontalScrollIndicator = NO;
    _pScrollView.canCancelContentTouches = NO;

    [self addSubview:_pScrollView];
    [_pScrollView addSubview:_pContentSizeView];
    [_pContentSizeView addSubview:_pLeftImageView];
    [_pContentSizeView addSubview:_pRightImageView];
    [self p_loadMarketBottomBarView];
    [self p_initConstraints];

    _pCacheArray = [NSMutableArray arrayWithCapacity:5];

    [self showLoopViews:@[[HZMinChartView class],[HZKLineChartView class],[HZStockInfoView class]]];
}
- (void)p_initConstraints
{
    [_pScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(self);
        make.bottom.mas_equalTo(_pMarketBottomBar.mas_top);
    }];
    [_pContentSizeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(_pScrollView);
        make.height.mas_equalTo(_pScrollView);
        make.width.mas_equalTo(_pScrollView).multipliedBy(2);
    }];
    [_pLeftImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.bottom.mas_equalTo(_pContentSizeView);
        make.right.mas_equalTo(_pRightImageView.mas_left);
    }];
    [_pRightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.right.bottom.mas_equalTo(_pContentSizeView);
        make.width.mas_equalTo(_pLeftImageView);
    }];
    
    [self.superview setNeedsLayout];
    [self.superview layoutIfNeeded];
}
- (void)p_saveOffset
{
    if (_nLeftIndex == 0) {
        _nOffsetMin = 0;
        _nOffsetKline = CGRectGetWidth(self.frame);
    }else if(_nLeftIndex == 1) {
        _nOffsetMin = CGRectGetWidth(self.frame);
        _nOffsetKline = 0;
    }
}
- (void)showRelatedChartViewWithTitle:(NSString *)title
{
    if ([title isEqual:@"分时"]) {
        _pScrollView.contentOffset = CGPointMake(_nOffsetMin, 0);
    }else {
        _pScrollView.contentOffset = CGPointMake(_nOffsetKline, 0);
    }
}
- (void)p_removeLandscapeView
{
    [_pLandscapeChartView removeFromSuperview];
    _pLandscapeChartView = nil;
}
- (NSString *)p_getCurrentStateTitle
{
    NSString *title = nil;
    if (_pScrollView.contentOffset.x == _nOffsetMin) {
        title = @"分时";
    }else {
        for (UIView *cacheView in _pCacheArray) {
            if ([cacheView isMemberOfClass:[HZKLineChartView class]]) {
                HZKLineChartView *KChartView = (HZKLineChartView *)cacheView;
                title = [KChartView getStateTitle];
                break;
            }
        }
    }
    
    return title;
}
- (int)p_getIndexState
{
    int nState = 0;
    for (UIView *cacheView in _pCacheArray) {
        if ([cacheView isMemberOfClass:[HZKLineChartView class]]) {
            HZKLineChartView *KChartView = (HZKLineChartView *)cacheView;
            nState = [KChartView getIndexState];
            break;
        }
    }
    return nState;
}
- (void)p_updateCancelLandscapeDataWithTite:(NSString *)title
{
    if ([title isEqualToString:@"分时"]) {
        for (UIView *cacheView in _pCacheArray) {
            if ([cacheView isMemberOfClass:[HZMinChartView class]]) {
                HZMinChartView *minChartView = (HZMinChartView *)cacheView;
                [minChartView updateMinData];
                break;
            }
        }
        return;
    }
    for (UIView *cacheView in _pCacheArray) {
        if ([cacheView isMemberOfClass:[HZKLineChartView class]]) {
            HZKLineChartView *KChartView = (HZKLineChartView *)cacheView;
            [KChartView updateNewData:[HZDataTool p_parseKLineData]];
            [KChartView updateRadioButtonWithTitle:title];
            break;
        }
    }
}
- (void)p_updateIndexCancelLandscapeDataWithState:(int)state
{
    for (UIView *cacheView in _pCacheArray) {
        if ([cacheView isMemberOfClass:[HZKLineChartView class]]) {
            HZKLineChartView *KChartView = (HZKLineChartView *)cacheView;
            [KChartView updateIndexWithState:state];
            break;
        }
    }
}

- (void)bindCodeInfo:(HZOwnedStockModel *)codeInfo
{
    _pOwnModel = codeInfo;
    _pMarketBottomBar.logicManager = self.logicManager;
    [_pMarketBottomBar bindCodeInfo:codeInfo];
}
- (void)p_sendInfoWithWithObjc:(id)objc withType:(NSInteger)type withParamter:(id)paramter
{
    if (![objc isKindOfClass:[NSNumber class]]) {
        return;
    }
    kHZApiType nApiType = [objc integerValue];
    switch (nApiType) {
        case kHZApi_MinPrice_Type:
        {
            if ([paramter isKindOfClass:[HZMinPriceModel class]] && paramter) {
                HZMinPriceModel *pMinPriceModel = paramter;
                _pMinPriceModel = pMinPriceModel;
                [_pLandscapeChartView updatePriceData:pMinPriceModel fromType:KFromMinType];
                
                for (UIView *cacheView in _pCacheArray) {
                    if ([cacheView isMemberOfClass:[HZMinChartView class]]) {
                        HZMinChartView *minChartView = (HZMinChartView *)cacheView;
                        [minChartView bindCodeInfo:_pOwnModel];
                        [minChartView updateNewData:pMinPriceModel];
                        break;
                    }
                }
            }
        }
            break;
        case kHZApi_MinDetail_Type:
        {
            if (_pOwnModel.nModel_Style == 1) {return;}
            for (UIView *cacheView in _pCacheArray) {
                if ([cacheView isMemberOfClass:[HZMinChartView class]]) {
                    HZMinChartView *minChartView = (HZMinChartView *)cacheView;
                    [minChartView bindCodeInfo:_pOwnModel];
                    [minChartView updateDetailData:paramter];
                    break;
                }
            }
        }
            break;
        case kHZApi_Min_Type:
        {
            if (_isLandscape) {
                [_pLandscapeChartView updateMinData];
                return;
            }
            for (UIView *cacheView in _pCacheArray) {
                if ([cacheView isMemberOfClass:[HZMinChartView class]]) {
                    HZMinChartView *minChartView = (HZMinChartView *)cacheView;
                    [minChartView updateMinData];
                    break;
                }
            }
        }
            break;
        case kHZApi_KLine_Type:
        {
            HZMinPriceModel *model = nil;
            if ([paramter isKindOfClass:[HZMinPriceModel class]]) {
                model = (HZMinPriceModel *)paramter;
                _pKPriceModel = model;
            }
            if (_isLandscape) {
                [_pLandscapeChartView updateKLineData];
                [_pLandscapeChartView updatePriceData:model fromType:KFromKLineType];

                return;
            }
            for (UIView *cacheView in _pCacheArray) {
                if ([cacheView isMemberOfClass:[HZKLineChartView class]]) {
                    HZKLineChartView *KChartView = (HZKLineChartView *)cacheView;
                    [KChartView updateNewData:model];
                    break;
                }
            }
        }
            break;
        case kHZApi_IndexZhangFuTop_Type:
        case kHZApi_IndexDieFuTop_Type:
        case kHZApi_IndexHuanShouTop_Type:
        {
            if (_pOwnModel.nModel_Style != 1) {return;}
            for (UIView *cacheView in _pCacheArray) {
                if ([cacheView isMemberOfClass:[HZMinChartView class]]) {
                    HZMinChartView *minChartView = (HZMinChartView *)cacheView;
                    [minChartView bindCodeInfo:_pOwnModel];
                    [minChartView p_sendInfoWithWithObjc:objc withType:type withParamter:paramter];
                    break;
                }
            }
        }
            break;
            
        default:
            break;
    }
}
#pragma mark -
- (void)upToParentWithObjc:(id)objc withType:(NSInteger)type withParamter:(id)paramter{
    switch (type) {
        case kHZ_setLandscapeScreen_Action:
        {
            _isLandscape = YES;
            [self p_saveOffset];
            [self p_loadLandscapeChartView];
            NSString *title = [self p_getCurrentStateTitle];
            [self.parent upToParentWithObjc:objc withType:type withParamter:paramter];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.superview setNeedsLayout];
                [self.superview layoutIfNeeded];
                [_pLandscapeChartView updateNewDataWithStateTitle:title];
                [_pLandscapeChartView updateOwnModel:_pOwnModel];
                [_pLandscapeChartView updatePriceData:_pMinPriceModel kPriceData:_pKPriceModel];
                [_pLandscapeChartView updateIndexWithState:[self p_getIndexState]];
            });
        }
            break;
        case kHZ_jumpSingleStock_Action:
        case kHZ_ClickKLineRequest_Action:
        {
            [self.parent upToParentWithObjc:objc withType:type withParamter:paramter];
        }
            break;
        case kHZ_cancelLandscapeScreen_Action:
        {
            NSArray *params = (NSArray *)paramter;
            _isLandscape = NO;
            [self p_removeLandscapeView];
            [self.parent upToParentWithObjc:objc withType:type withParamter:paramter];
            [self showRelatedChartViewWithTitle:params[0]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.superview setNeedsLayout];
                [self.superview layoutIfNeeded];
                [self p_updateCancelLandscapeDataWithTite:paramter[0]];
                [self p_updateIndexCancelLandscapeDataWithState:[paramter[1] intValue]];
            });
        }
            break;
            
        default:
            break;
    }
}
- (void)downToChildWithObjc:(id)objc withType:(NSInteger)type withParamter:(id)paramter{
    switch (type) {
        case kHZ_updateNewData_Action:
        {
            [self p_sendInfoWithWithObjc:objc withType:type withParamter:paramter];
        }
            break;
        default:
            break;
    }
}
 

@end
